package com.tianji.learning.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.tianji.api.client.user.UserClient;
import com.tianji.api.dto.user.UserDTO;
import com.tianji.common.domain.R;
import com.tianji.common.domain.dto.PageDTO;
import com.tianji.common.exceptions.BizIllegalException;
import com.tianji.common.exceptions.DbException;
import com.tianji.common.utils.BeanUtils;
import com.tianji.common.utils.CollUtils;
import com.tianji.common.utils.UserContext;
import com.tianji.learning.domain.dto.ReplyDTO;
import com.tianji.learning.domain.po.InteractionQuestion;
import com.tianji.learning.domain.po.InteractionReply;
import com.tianji.learning.domain.query.ReplyPageQuery;
import com.tianji.learning.domain.vo.QuestionVO;
import com.tianji.learning.domain.vo.ReplyVO;
import com.tianji.learning.enums.QuestionStatus;
import com.tianji.learning.mapper.InteractionQuestionMapper;
import com.tianji.learning.mapper.InteractionReplyMapper;
import com.tianji.learning.service.IInteractionReplyService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import io.swagger.models.auth.In;
import lombok.RequiredArgsConstructor;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 互动问题的回答或评论 服务实现类
 * </p>
 *
 * @author yp
 * @since 2024-07-23
 */
@Service
@RequiredArgsConstructor
public class InteractionReplyServiceImpl extends ServiceImpl<InteractionReplyMapper, InteractionReply> implements IInteractionReplyService {
    private final InteractionQuestionMapper questionMapper;
    private final UserClient userClient;

    /**
     * 新增回复
     *
     * @param replyDTO
     */
    @Override
    @Transactional
    public void addReply(ReplyDTO replyDTO) {

        Long questionId = replyDTO.getQuestionId();
        InteractionReply reply = BeanUtils.copyBean(replyDTO, InteractionReply.class);
        Long user = UserContext.getUser();
        reply.setUserId(user);
        save(reply);
        InteractionQuestion question = questionMapper.selectById(questionId);
        //5.封装QuestionVO

        if (questionId != null && replyDTO.getAnswerId() == null) {
            if (question != null) {
                question.setLatestAnswerId(reply.getId());
                int times = question.getAnswerTimes() + 1;
                question.setAnswerTimes(times);
                question.setId(questionId);
            }
        } else {
            Long answerId = replyDTO.getAnswerId();
            if (answerId != null) {
                InteractionReply reply1 = getById(answerId);
                reply1.setId(answerId);
                Integer replyTimes = reply1.getReplyTimes() + 1;
                reply1.setReplyTimes(replyTimes);
                updateById(reply1);
            }
        }
        if (replyDTO.getIsStudent()) {
            if (question != null) {
                question.setStatus(QuestionStatus.UN_CHECK);
                questionMapper.updateById(question);
            }
        }

    }

    @Override
    public PageDTO<ReplyVO> queryRepky(ReplyPageQuery pageQuery) {
        Long questionId = pageQuery.getQuestionId();
        Long answerId = pageQuery.getAnswerId();
        if (questionId == null && answerId == null) {
            throw new BizIllegalException("参数有误");
        }
        Page<InteractionReply> page = lambdaQuery()
                .eq(questionId != null, InteractionReply::getQuestionId, questionId)
                .eq(answerId != null, InteractionReply::getAnswerId, answerId)
                .eq(InteractionReply::getCreateTime, false)
                .page(pageQuery.toMpPageDefaultSortByCreateTimeDesc());
        List<InteractionReply> replies = page.getRecords();
        if (replies == null) {
            throw new DbException("没有查询到数据库");
        }
        List<ReplyVO> voList = new ArrayList<>();
        Set<Long> userIds = new HashSet<>();
        Set<Long> answerIds = new HashSet<>();
        List<InteractionReply> answerlist = lambdaQuery()
                .eq(InteractionReply::getQuestionId, questionId)
                .list();
        for (InteractionReply reply : answerlist) {
            userIds.add(reply.getUserId());
            answerIds.add(reply.getId());
        }
        //存储reply对象
        Map<Long, InteractionReply> replylist = new HashMap<>();
        if (CollUtils.isNotEmpty(answerlist)) {
            replylist = answerlist.stream().collect(Collectors.toMap(InteractionReply::getId, u -> u));
        }
        //存储全部user对象

        Map<Long, UserDTO> userIdslists = new HashMap<>();
        List<UserDTO> userDTOS = userClient.queryUserByIds(userIds);
        if (CollUtils.isNotEmpty(userDTOS)) {
            userIdslists = userDTOS.stream().collect(Collectors.toMap(UserDTO::getId, l -> l));
        }

        for (InteractionReply reply : answerlist) {
            ReplyVO vo = BeanUtils.copyBean(reply, ReplyVO.class);
            if (!reply.getAnonymity()) {
                UserDTO userDTO = userIdslists.get(reply.getUserId());
                vo.setUserName(userDTO.getUsername());
                vo.setUserIcon(userDTO.getIcon());
                if (reply.getTargetUserId() != null) {
                    UserDTO userDTO1 = userIdslists.get(reply.getTargetUserId());
                    if (userDTO1 != null) {
                        vo.setTargetUserName(userDTO1.getUsername());
                    }
                }
            }
            voList.add(vo);
        }

        return PageDTO.of(page, voList);
    }
}
